<?php
/**
 * Created by PhpStorm.
 * User: DaibiDaddy
 * Date: 2016/5/24
 * Time: 17:14
 */

namespace App\Base;

use App\Entity\User;
use App\Model\LazyCommon\AdminLogModel;
use App\Model\LazyCommon\CCM;
use App\Model\LazyCommon\UserModel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class BaseController4MiniApp extends BaseController4App {

    /**
     * @param $token
     * @return User|null|object
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function checkToken($token)
    {
        $UserModel = new UserModel($this->getDoctrine());
        $user = $UserModel->getRep()->findOneBy(array("account"=>$token));
        if (!$user) {
            $user = new User();
            $defaultInsertData = array(
                "account"   => $token,
                "password"  => "",
                "passwordPay"  => "",
                "groups"  => 3,
                "addTime"  => time() + 3 * 24 * 3600,
                "headPic"  => "/public/default_user.png",
                "level"  => 0,
                "parent"  => 0,
                "lastLoginTime"  => 0,
                "lastLoginIp"  => "",
            );
            foreach ($defaultInsertData as $key => $val) {
                $func = "set".ucfirst($key);
                $user->$func($val);
            }
        }
        $this->myEm()->persist($user);
        $this->myEm()->flush();
        return $user;
    }

    /**
     * @return User|null|object
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function init()
    {
        $request = Request::createFromGlobals();
        $token = $request->headers->get("access-token");
        if ($token) {
            return $user = $this->checkToken($token);
        }else{
            $data = array(
                "s"=> 203,
                "i"  => "登录信息失效",
                "d"  => "",
            );
            die( new Response(json_encode($data),200,array("content-type"=>"application/json")));
        }

    }

    /**
     * @return User|mixed|null|object
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function getUser()
    {
        return $this->init();
    }
}
